<template>
  <div class="tui-input-container">
    <input :id="formItemId" :name="name" :type="type" v-model="localValue" :placeholder="placeholder" :disabled="disabled" :required="required" :readonly="readonly" :maxlength="maxlength" :minlength="minlength" :pattern="pattern" :autocomplete="autocomplete" class="tui-input" @input="handleInput" @focus="handleFocus" @blur="handleBlur" />
  </div>
</template>

<script lang="ts" setup>

import type { TuiInputProps } from './types';
import { useRegisterField, useModelValue, useFormItemId, useValidateField } from './helpers';
import { throttle } from '../../flow/timing';

// 使用withDefaults设置默认值
const props = withDefaults(defineProps<TuiInputProps>(), {
  name: '',
  type: 'text',
  modelValue: '',
  placeholder: '',
  disabled: false,
  required: false,
  readonly: false,
  maxlength: undefined,
  minlength: undefined,
  pattern: undefined,
  autocomplete: 'off'
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | number): void;
  (e: 'focus', event: FocusEvent): void;
  (e: 'blur', event: FocusEvent): void;
  (e: 'input', event: Event): void;
  (e: 'validate', fieldName: string, value: string | number): void;
}>();

// 使用modelValue组合式函数处理v-model绑定
const localValue = useModelValue(props, 'modelValue');

// 使用formItemId组合式函数处理表单项目ID
const formItemId = useFormItemId(props, 'id');

// 使用validateField组合式函数获取字段验证方法
const validateField = useValidateField('validateField');

// 使用字段注册组合式函数
useRegisterField(props.name);

// 使用节流函数处理输入事件，限制触发频率
const handleInput = throttle((event: Event) => {
  // 由于使用了v-model，值会自动更新到localValue
  emit('input', event);

  emit('update:modelValue', localValue.value);

  // 触发验证事件，让父组件决定何时验证
  emit('validate', props.name, localValue.value);

  // 直接调用验证方法，确保验证通过时错误信息被清除
  validateField(props.name, localValue.value);
}, 300);

// 处理聚焦事件
const handleFocus = (event: FocusEvent) => {
  emit('focus', event);
};

// 处理失焦事件
const handleBlur = (event: FocusEvent) => {
  emit('blur', event);
  // 失焦时也可以考虑进行验证
  validateField(props.name, localValue.value);
};
</script>

<style scoped>
.tui-input-container {
  display: flex;
  align-items: center;
}

.tui-input-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.tui-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--tui-color-border);
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
  transition: border-color 0.3s;
}

.tui-input:focus {
  outline: none;
  border-color: var(--tui-color-primary);
  box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
}

.tui-input:disabled {
  background-color: var(--tui-color-bg-light);
  cursor: not-allowed;
}

.tui-input-error {
  color: var(--tui-color-danger);
  font-size: 12px;
  margin-top: 4px;
  margin-bottom: 0;
}
</style>